package bb.lanxing.calc.processer;

import bb.lanxing.calc.data.DisplayPoint;
import bb.lanxing.calc.data.SourcePoint;
import bb.lanxing.model.WorkoutDatabaseHelper;
import bb.lanxing.model.database.Trackpoint;
import bb.lanxing.util.CommonUtil;
import bb.lanxing.util.Log;
import java.util.ArrayList;
import java.util.List;

public class StaticWorkoutProcessor extends BaseWorkoutProcessor {
    final static private String TAG = "StaticWorkoutProcessor";
    private static final int MIN_STORE_NUM = 500;
    private final List<Trackpoint> locationList = new ArrayList<>();

    @Override
    public boolean checkPoint(SourcePoint sourcePoint) {
        if (isTrainingMode() 
            || isIndoorBikeMode()
            || isCrossTrainerMode()
            || CommonUtil.isPointValid(sourcePoint)) {
            this.sourcePointPair.update(sourcePoint);
            return true;
        }
        return false;
    }

    @Override
    public DisplayPoint process(SourcePoint sourcePoint) {
        if (checkPoint(sourcePoint)) {
            calcPoint(sourcePoint);
            calcWorkout(sourcePoint);
            storePoint(sourcePoint);
            return null;
        }
        return null;
    }

    @Override
    public void storePoint(SourcePoint sourcePoint) {
        this.locationList.add(makeTrackpoint(this.workout, sourcePoint));
        Log.d(TAG, "storePoint, locationList.size() = " + this.locationList.size());
        if (this.locationList.size() >= MIN_STORE_NUM) {
            int vCount = WorkoutDatabaseHelper.saveTrackPoints(this.locationList);
            this.locationList.clear();
            WorkoutDatabaseHelper.save(this.workout);
            Log.d(TAG, "storePoint, vCount=" + vCount);
        }
    }

    @Override
    public void calcWorkout(SourcePoint sourcePoint) {
        long timestamp = sourcePoint.getTimestamp();
        if (this.workout.getStartTime() == 0) {
            this.workout.setStartTime(timestamp);
        }
        this.workout.setEndTime(timestamp);
        setWorkoutSource(this.workout, sourcePoint);
        this.workout.setStep(sourcePoint.getSteps());
        processBleData(this.workout, sourcePoint);
        sourcePoint.setDistance(this.workout.getDistance());
        sourcePoint.setDuration(this.workout.getDuration());
        sourcePoint.setElevationGain(this.workout.getElevationGain());
        sourcePoint.setElevationLoss(this.workout.getElevationLoss());
    }

    @Override
    public void flushPoint(boolean sync) {
        if (!this.locationList.isEmpty()) {
            Log.d(TAG, "flushPoint: SIZE=" + locationList.size());
            int vCount = WorkoutDatabaseHelper.saveTrackPoints(this.locationList);
            Log.d(TAG, "flushPoint: SAVE FINISHED...vCount=" + vCount);
            this.locationList.clear();
        }
    }
}
